<?php
use Firebase\JWT\JWT;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use Qiniu\Auth;

//function toJson($request, $data, $status = 0, $message = '')
//{
//    $json = ['status' => $status, 'message' => $message, 'data' => $data];
//
//    return response()
//        ->json($json)
//        ->setCallback($request->input('callback'));
//}

function toJSON($data = '', $code = 0, $message = '')
{
    if (empty($message)) {
        $message = \Constant::getMsg($code);
    }

    if ($data == '') $data = null;

    return ['code' => $code, 'message' => $message, 'data' => $data];
}

function encodeToken($user)
{
    $payload = [
        'id' => $user->id,
        'mobile' => $user->mobile,
        'nickname' => $user->nickname,
    ];

    return JWT::encode($payload, env('APP_KEY'));
}

function decodeToken($token)
{
    return JWT::decode($token, env('APP_KEY'), array('HS256'));
}


function checkMobile($mobile)
{
    if(preg_match("/^1[2345789]{1}\d{9}$/", $mobile))
        return true;

    return false;
}


function getRedis($id)
{
    //$conn =  'conn_' . $id % 16;
    $conn = 'conn';
    return Redis::connection($conn);
}

function getTableId($mobile, $max = 16)
{
    $crc = sprintf("%u", crc32($mobile));
    $id = intval(fmod($crc, $max));

    return $id + 1;
}

function getUserIdSequence()
{
    $db = DB::connection(env('DB_CONNECTION'));
    $db->update("REPLACE INTO `mm_user_id_sequence` (`stub`) VALUES ('a')");
    $row = $db->selectOne('SELECT LAST_INSERT_ID() AS `id`');
    return $row->id;
}

function generateOrderSn() {
    return date('ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
}

function getQiniuUploadToken() {

    $accessKey = env('QINIU_AK');
    $secretKey = env('QINIU_SK');
    $bucket = env('QINIU_BUCKET');

    $auth = new Auth($accessKey, $secretKey);

    return $auth->uploadToken($bucket);

}

function getCss() {
    return <<<EOF
<html>
<head>
<title></title>
<style type="text/css">
    img{display:block; border:0; margin:0 auto; max-width:100%;width:100%;text-align:center; vertical-align:middle;}
    body{padding:5px; top:0; margin:0; background-color:transparent;}
</style>
</head>
<body style='color:#333333;line-height:150%;font-size:16px;'>[content]</body>
</html>
EOF;
}



